import json
import requests

def main():
    with open('hubei2.geojson','r') as fr:
        all = json.loads(fr.read())['features']

    for item in all:
        area = 0
        if item['geometry']['type'] == 'MultiPolygon':
            maxLen = 0
            for k in range(0, len(item['geometry']['coordinates'])):
                geom = item['geometry']['coordinates'][k][0]
                xf, yf, areaf = calcCentroid(geom)
                area += areaf
                if len(geom) > maxLen:
                    maxLenIdx = k
                    maxLenItem = geom
                    maxLen = len(geom)

            cx, cy, areaf = calcCentroid(maxLenItem)
        if item['geometry']['type'] == 'Polygon':
            geom = item['geometry']['coordinates'][0]
            cx, cy, area = calcCentroid(geom)
        item['properties']['centroid'] = [cy, cx]
        item['properties']['area'] = area

        if item['properties']['admin-level'] == 'city':
            areaName = item['properties']['city']
        elif item['properties']['admin-level'] != 'province':
            areaName = item['properties']['district']
        url = 'http://restapi.amap.com/v3/config/district?key=de1fb1729e2e4f6fb20d2e6ea3ac8e27&keywords=' + areaName + '&subdistrict=0&extensions=base'
        response = requests.get(url)
        result = response.json()

        item['properties']['center'] = [float(x) for x in result['districts'][0]['center'].split(',')]
    with open('hubei3.geojson','w') as fw:
        fw.write(json.dumps({'type':'FeatureCollection', 'features':all}, separators=(',',':'), ensure_ascii=False))
def calcCentroid(geom):

    area = 0
    Gx = 0.0
    Gy = 0.0
    for i in range(0, len(geom)):
        iLat = geom[i][1]
        iLng = geom[i][0]
        if i != len(geom) - 1:
            nextLat = geom[i + 1][1]
            nextLng = geom[i + 1][0]
        else:
            nextLat = geom[0][1]
            nextLng = geom[0][0]
        temp = (iLat * nextLng - iLng * nextLat) / 2.0

        area += temp
        Gx += temp * (iLat + nextLat) / 3.0
        Gy += temp * (iLng + nextLng) / 3.0
    Gx = Gx / area
    Gy = Gy / area
    return Gx, Gy, area

if __name__ == '__main__':
    main()